package org.example.filter;


import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import org.example.entity.CommonResult;
import org.example.entity.LoginUser;
import org.example.utils.JwtUtil;
import org.example.utils.RedisCache;
import org.example.utils.WebUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String username;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            username = claims.getSubject();
        } catch (Exception e) {
            //放行
            e.printStackTrace();
            throw new RuntimeException("非法的token");
        }
        //从redis中获取用户信息
        String rediskey = "work:" + username;
        LoginUser loginUser = this.redisCache.getCacheObject(rediskey);
        if (loginUser == null) {
//            throw new RuntimeException("用户未登录");
            CommonResult<Object> result = new CommonResult<>(HttpStatus.HTTP_UNAUTHORIZED, "用户token过期，请重新登录");
            String jsonString = JSON.toJSONString(result);
            WebUtils.printContent(response, jsonString);
            return;
        }
        //存入SecurityContextHolder
        //获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //放行
        filterChain.doFilter(request, response);
    }
}

